<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>防抖</title>
</head>

<body>
    <input type="text" id="input1">

</body>
<script>
    // 用户暂停几秒后才触发事件
    // let timer = null
    // const input1 = document.getElementById('input1')
    // input1.addEventListener('keyup', function () {
    //     if(timer){
    //         clearTimeout(timer)
    //     }
    //     timer =  setTimeout(() => {
    //         console.log(input1.value)
    //         timer = null
    //     }, 500);
    // })

    // 防抖封装
    function debounce(fn,delay = 500){
        let timer = null
        return function(){
            if(timer){
                clearTimeout(timer)
            }
            timer = setTimeout(() => {
                fn.apply(this,arguments)
                timer = null
            }, delay);
        }
    }
    input1.addEventListener('keyup',debounce(()=>{
        console.log(input1.value)
    },500))





</script>

</html>